package com.zuoshenge.main.service;

import com.zuoshenge.main.dao.CourseDao;
import com.zuoshenge.main.dao.CourseRecordsDao;
import com.zuoshenge.main.dto.CourseSelectionDTO;
import com.zuoshenge.main.entity.Course;
import com.zuoshenge.main.entity.CourseRecords;
import com.zuoshenge.redis.util.RedisUtil;
import com.zuoshenge.tool.excel.ExcelImportService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class CourseService implements ExcelImportService<Course> {

    @Resource
    private CourseDao courseDao;
    @Resource
    private CourseRecordsDao courseRecordsDao;
    @Resource
    private RedisUtil redisUtil;
    @Value("${redis.keys.course-quota-key}")
    private String COURSE_QUOTA_KEY;

    public Long queryCount(Map<String, Object> conditions) {
        Course course = new Course();
        return courseDao.count(course);
    }

    public List<Course> queryByPage(Course course, Long pageNo, Long pageSize) {
        Long pageStart = (pageNo - 1L) * pageSize;
        return courseDao.queryAllByLimit(course, pageStart, pageSize);
    }

    // 使用Spring的事务管理进行批量插入
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchInsert(List<Course> batch) {
        courseDao.insertBatch(batch);
    }

    public Long count(Course course) {
        return courseDao.count(course);
    }

    @Override
    public int countByColumn1(String column1) {
        return (int) courseDao.count(new Course());
    }

    public List<Course> queryAll() {
        return courseDao.queryAll();
    }

    @Transactional
    public Integer courseSelection(CourseSelectionDTO courseSelectionDTO) {
        int count = courseDao.courseSelection(courseSelectionDTO.getCid(), courseSelectionDTO.getSid());
        if (count == 0) {
            return 0;
        } else {
            redisUtil.increment(COURSE_QUOTA_KEY+courseSelectionDTO.getCid());
            CourseRecords courseRecords = new CourseRecords(
                    null,
                    courseSelectionDTO.getSid(),
                    courseSelectionDTO.getCid()
            );
            return courseRecordsDao.insert(courseRecords);
        }
    }

    public Integer checkSelectionStatus(CourseSelectionDTO courseSelectionDTO) {
        return courseRecordsDao.queryBySidAndCId(courseSelectionDTO.getSid(), courseSelectionDTO.getCid());
    }
}
